import subprocess
from pathlib import Path
import os

def merge_with_codec_info(
    video_m4s: str,
    audio_m4s: str,
    output_mp4: str,
    video_codec: str = "hev1.1.6.L150.90",
    audio_codec: str = "mp4a.40.2",
    crf: int = 18,  # 0-51，值越小质量越高
):
    """
    根据编码信息高质量合并音视频
    
    :param crf: 视频质量参数（18-28为推荐范围）
    """
    # 解析视频编码参数
    vcodec_map = {
        "hev1": "libx265",
        "avc1": "libx264",
    }
    v_profile = video_codec.split(".")[1]
    v_level = video_codec.split(".")[3].lstrip("L")

    # 构建FFmpeg命令
    cmd = [
        "ffmpeg",
        "-i", str(video_m4s),
        "-i", str(audio_m4s),
        "-c:v", vcodec_map.get(video_codec[:4], "copy"),
        "-profile:v", f"main",  # hev1对应main profile
        "-level:v", v_level,
        "-x265-params", f"crf={crf}:psy-rd=1.5",  # H.265高级参数
        "-c:a", "aac",
        "-profile:a", "aac_low",  # mp4a.40.2对应AAC-LC
        "-movflags", "+faststart",
        "-y",
        str(output_mp4)
    ]

    # 执行命令
    try:
        result = subprocess.run(
        cmd, 
        check=True, 
        capture_output=True, 
        text=True,
        encoding='utf-8',
        errors='ignore'  # 忽略无法解码的字符
    )
        print(f"合并成功：{output_mp4}")
    except subprocess.CalledProcessError as e:
        print(f"合并失败：{e.stderr}")

def list_files(dir_path, file_ext):
    """使用pathlib列出.m4s文件（不区分大小写）"""
    path = Path(dir_path)
    return [f.name for f in path.glob(f'*.{file_ext}')]  # 或使用 '*.m4s' 匹配大小写

def batch_merge(file_dir_path):
    file_list = list_files(file_dir_path, 'm4s')
    name_list = [str(f).replace('_aduio.m4s', '').replace('.m4s', '') for f in file_list]
    deal_list = []
    for name in name_list:
        if name in deal_list:
            continue
        print(name)
        deal_list.append(name)
        merge_with_codec_info(
        video_m4s=f"{file_dir_path}/{name}.m4s",
        audio_m4s=f"{file_dir_path}/{name}_aduio.m4s",
        output_mp4=f"{file_dir_path}/{name}.mp4",
        video_codec="hev1.1.6.L150.90",
        audio_codec="mp4a.40.2",
        crf=20,  # 平衡质量与文件大小
    )



# 使用示例
if __name__ == "__main__":
    # 使用示例
    # merge_with_codec_info(
    #     video_m4s="D:/workspace/learning/python-learning/广播剧_有声书_穿越_修仙_爽文，多人有声剧_哔哩哔哩_bilibili/001-.第5季·预告旧的回忆.m4s",
    #     audio_m4s="D:/workspace/learning/python-learning/广播剧_有声书_穿越_修仙_爽文，多人有声剧_哔哩哔哩_bilibili/001-.第5季·预告旧的回忆_aduio.m4s",
    #     output_mp4="output_hq.mp4",
    #     video_codec="hev1.1.6.L150.90",
    #     audio_codec="mp4a.40.2",
    #     crf=20,  # 平衡质量与文件大小
    # )

    batch_merge('./【有声书】《巅峰仙侠爽文》全集，多人有声剧_哔哩哔哩_bilibili')
    # 案例1：基本合并
    # output1 = merger.merge(
    #     video_m4s="30643454602-1-30232.m4s",
    #     audio_m4s="30643454602-1-30280.m4s",
    # )

    # 案例2：使用init.mp4确保元数据完整
    # output2 = merger.merge(
    #     video_m4s="./广播剧_有声书_穿越_修仙_爽文，多人有声剧_哔哩哔哩_bilibili/001-.第5季·预告旧的回忆.m4s",
    #     audio_m4s="./广播剧_有声书_穿越_修仙_爽文，多人有声剧_哔哩哔哩_bilibili/001-.第5季·预告旧的回忆_audio.m4s",
    #     # video_init="30643454602-1-30232_init.mp4",
    #     # audio_init="30643454602-1-30280_init.mp4",
    #     # output_path="custom_output.mp4",
    # )

    # print(f"合并完成：\n- {output1}\n- {output2}")